//
//  DNBaseTextField.swift
//  LunalerApp
//
//  Created by 露乐ios on 2018/2/9.
//  Copyright © 2018年 露乐ios. All rights reserved.
//

import UIKit

@objc protocol DNBaseTextFieldDelegate : NSObjectProtocol {
    
    @objc optional func configGlobleFormatStr(formatStr:NSString) -> Void
    
    @objc optional func baseTextFiedlDidchangeText(textField:DNBaseTextField,text:NSString)
    
    @objc optional func baseTextFieldDidFinshWithNumber(textField:DNBaseTextField,number:NSString)
    
    @objc optional func baseTextFieldShouldReturn(textField:DNBaseTextField)
}

fileprivate extension Selector
{
    static let textFieldDidChange = #selector(DNBaseTextField.textFieldDidChange);
}

class DNBaseTextField: UITextField ,DNBaseTextFieldDelegate,UITextFieldDelegate{

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    public let UCSTextFieldSeparateCharacter = " "
    
    var numbers : NSString{
        get{
            return self.removeSpaceCharacter(originalString: self.text! as NSString)
        }
    }  //返回无空格的字符串
    var baseDelegate : DNBaseTextFieldDelegate?
    
    fileprivate lazy var defaultFormatStr : NSString = {
        return ""
    }()
    
    fileprivate var formatStrs : NSArray = {
        let tempArr = NSArray()
        return tempArr
    }()
    
    fileprivate var numberCount = 0
    
 
    func setBaseNumber(number:NSString) {
        self.text = "";
        for i in 0..<number.length {
            let txfStr  : NSString = self.text! as NSString
            self.text = txfStr.appending(number.substring(with: NSRange.init(location: i, length: 1)))
            self.p_adjustContent()
        }
    }
    
    func setGlobleFormatStr(defaultFormatStr:NSString) {
        self.defaultFormatStr = defaultFormatStr
        self.numberCount = self.removeSpaceCharacter(originalString: self.defaultFormatStr).length
        self.p_configGlobleMes()
    }
    
    
     func configGlobleFormatStr(formatStr:NSString){
        print("\(#function)--请不要直接在基类中调用此方法,你需要在子类中重写此方法")
    }
    

    func removeSpaceCharacter(originalString:NSString) -> NSString {
        return originalString.dnStringByReplacingOccurrencesOfStringwithString(target: UCSTextFieldSeparateCharacter, replacement: "") as! NSString
    }
    
    @objc func textFieldDidChange(noti:NSNotification){
        let txf = noti.object as? UITextField
        let txfStr = txf!.text! as NSString
        let numbers = self.removeSpaceCharacter(originalString: txfStr)
        if numbers.length == self.numberCount {
            self.finishInputAction()
        }else{
            self.textchange()
        }
    }
    
    func finishInputAction(){
        if (self.baseDelegate?.responds(to: #selector(DNBaseTextFieldDelegate.baseTextFieldDidFinshWithNumber(textField:number:))))! {
            self.baseDelegate?.baseTextFieldDidFinshWithNumber!(textField: self, number: self.numbers)
        }
    }
    
    func p_configGlobleMes(){
        let tempArr = self.defaultFormatStr.components(separatedBy: self.UCSTextFieldSeparateCharacter) as NSArray
        self.formatStrs = tempArr.copy() as! NSArray
        
        self.delegate = self
        self.keyboardType = .phonePad
        NotificationCenter.default.addObserver(self, selector: .textFieldDidChange, name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
    }
    
    
    func p_adjustContent(){
        let tmpStr = self.text
        // 将类型转换为
        var countNum = 0
        self.formatStrs.enumerateObjects{ (str:Any, index:NSInteger, stop : UnsafeMutablePointer<ObjCBool>) in
            let tempStr = str as! NSString
            if tmpStr?.lengthOfBytes(using: .utf8) == countNum + tempStr.length + index * 1 && tempStr.length < self.defaultFormatStr.length{
                self.text = tmpStr?.appending(UCSTextFieldSeparateCharacter)
                countNum += 1
            }
            countNum += tempStr.length // 每次加一
        }
    }
    
    func p_appendStringWithRange(string:NSString,range:NSRange){
        let storateStr  = self.text! as NSString
        let selectedStr = storateStr.substring(with: range)
        let removeCount = self.removeSpaceCharacter(originalString: selectedStr as NSString).length // 要移除的数量
        
        let lastCount = self.numberCount - self.removeSpaceCharacter(originalString: self.text! as NSString).length + removeCount as NSInteger
        if lastCount <= 0 {
            return;
        }
        // 要粘贴字符串中非空格字符
        var strNoSpace : NSString = self.removeSpaceCharacter(originalString: string);
        
        // 设置需要的字符信息
        if strNoSpace.length > lastCount {
            strNoSpace = strNoSpace.substring(to: lastCount) as NSString
        }
        
        let newString : NSString = storateStr.replacingCharacters(in: range, with: strNoSpace as String) as NSString
        
        let newStrNoSpace = self.removeSpaceCharacter(originalString: newString)
        
        self.text = nil
        
        for i in 0...newStrNoSpace.length-1 {
            let  tempStr = newStrNoSpace;
            let  charStr = tempStr.substring(with: NSRange.init(location: i, length: 1))
            p_adjustContent()
            if (self.text?.lengthOfBytes(using: .utf8))! < self.numberCount + self.formatStrs.count - 1{
                self.text = (self.text! as NSString).appending(charStr)
                textchange()
            }
        }
    }
    
    func paste(sender : AnyObject){
        super.paste(sender)
        let noti = NSNotification.init(name: NSNotification.Name(rawValue: "pastNotification"), object: self)
        self.textFieldDidChange(noti: noti)
    }
    
    override func deleteBackward() {
        // 判断光标是不是在最尾部，不是的话就调整到尾部然后删除最后一个
        if (!(self.selectedTextRange?.start.isEqual(self.endOfDocument))!) {
            self.selectedTextRange = textRange(from: self.endOfDocument, to: self.endOfDocument)
            return
        }
        super.deleteBackward()
        
        if self.text!.lengthOfBytes(using: .utf8) > 0 {
            // 截取最后一个字符
            let txfStr = self.text! as NSString
            let lastChatacter = txfStr.dnSubStringWithRange(range: NSRange.init(location: txfStr.length-1, length: 1)) as! NSString
            if (lastChatacter.isEqual(to: UCSTextFieldSeparateCharacter as String)){
                self.text = txfStr.substring(to: txfStr.length-1)
            }
        }
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if (self.baseDelegate?.responds(to: #selector(DNBaseTextFieldDelegate.baseTextFiedlDidchangeText(textField:text:))))! {
            self.baseDelegate?.baseTextFiedlDidchangeText!(textField: self, text: self.numbers)
        }
        return true;
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if (self.baseDelegate?.responds(to: #selector(DNBaseTextFieldDelegate.baseTextFieldShouldReturn(textField:))))! {
            self.baseDelegate?.baseTextFieldShouldReturn!(textField: self)
        }
        return true;
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if (self.baseDelegate?.responds(to: #selector(DNBaseTextFieldDelegate.baseTextFiedlDidchangeText(textField:text:))))! {
            self.baseDelegate?.baseTextFiedlDidchangeText!(textField: self, text: self.numbers)
        }
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string == "" {
            return true
        }
        
        let currentLength : NSInteger = self.removeSpaceCharacter(originalString: textField.text! as NSString).length
        
        if currentLength - range.length >= self.numberCount && string.lengthOfBytes(using: .utf8) > 0 {
            self.finishInputAction()
            return false
        }else{
            self.textchange()
        }
        
        let strNoSpace = self.removeSpaceCharacter(originalString: string as NSString)
        
        let isDigital = self.isDigital(str: strNoSpace)
        if isDigital {
            if string.lengthOfBytes(using: .utf8) > 1 {
                self.p_appendStringWithRange(string: string as NSString, range: range)
                return false
            }else{
                self.p_adjustContent()
            }
        }
        return isDigital
    }
    
    func isDigital(str:NSString) -> Bool {
        let digital = "\\d+"
        let pre : NSPredicate = NSPredicate.init(format: "SELF MATCHES%@", digital)
        return pre.evaluate(with:str)
    }
    
    func textchange(){
        
        if (self.baseDelegate?.responds(to: #selector(DNBaseTextFieldDelegate.baseTextFiedlDidchangeText(textField:text:))))! {
            self.baseDelegate?.baseTextFiedlDidchangeText!(textField: self, text: self.numbers)
        }
    }
    
 
    
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
    }
    
}
